<?php

namespace App\Import;

use App\Http\Controllers\Machine\RefundSignController;
use App\Http\Resources\GoodsModelResource;
use App\Models\GoodsPicPrimaryModel;
use App\Models\GoodsSpecModel;
use App\Models\Refund\RefundSignDetailModel;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
class RefundSignImport implements ToCollection
{
    /**
     * 执行导入
     * @param Collection $collection
     * @return void
     */
    public function collection(Collection $collection): void
    {
        $data = [];
        $orderNo = date('YmdHi');
        $excelArray = $collection->toArray();
        $goodsDataList = $this->getGoodsDataArray($excelArray);
        $supplyCollection = RefundSignController::getSupplyDataCache();
        foreach ($excelArray as $v) {
            if ($v[0] == '图片' || empty($v[6]))
                continue;
            $goods = $this->getGoodsItemData($goodsDataList, $v, $supplyCollection);
            $total = floatval($goods['price'] * trim($v[5]));
            $data[] = [
                'sid'           => $goods['sid'],
                'order_no'      => $orderNo,
                'goods_id'      => $goods['goods_id'],
                'goods_name'    => $goods['goods_name'],
                'goods_sn'      => $goods['goods_sn'],
                'thumbnail'     => $goods['thumbnail'],
                'color'         => $goods['color'],
                'size'          => $goods['size'],
                'weight'        => $goods['weight'],
                'price'         => $goods['price'],
                'goods_num'     => trim($v[5]),
                'total'         => $total,
                'doned_uid'     => 0,
                'created_at'    => date('Y-m-d H:i:s'),
                'updated_at'    => date('Y-m-d H:i:s')
            ];
        }
        RefundSignDetailModel::insert($data);
    }

    /**
     * 格式化商品数据
     * @param $goodsDataList
     * @param $goods
     * @param $supplyCollection
     * @return array
     */
    private function getGoodsItemData($goodsDataList, $goods, $supplyCollection): array
    {
        $sName = $goods[1];
        $goodsSns = array_column($goodsDataList, 'goods_sn');
        $searchGoodsSnKey = array_search($goods[6], $goodsSns);
        if ($searchGoodsSnKey !== false)
            return $goodsDataList[$searchGoodsSnKey];
        else {
            $supplyCollection = $supplyCollection->filter(function ($item) use ($sName) {
                return str_contains($item->CName, $sName);
            });
            $sid = $supplyCollection->isEmpty() ? 0 : $supplyCollection->first()->ID;
            $colorSize = explode(';', $goods[3]);
            return [
                'goods_id'  => 0,
                'goods_name'=> $goods[2],
                'goods_sn'  => $goods[6],
                'sid'       => $sid,
                'color'     => $colorSize[0] ?? '',
                'size'      => $colorSize[1] ?? '',
                'weight'    => 0,
                'price'     => $goods[4],
                'thumbnail' => $goods[0],
            ];
        }
    }

    /**
     * 获取商品规格详细信息
     * @param $array
     * @return array
     */
    private function getGoodsDataArray($array): array
    {
        $goodsSns = $this->getGoodsSns($array);
        $specCollection = GoodsSpecModel::whereIn('goods_sn', $goodsSns)->select(['goods_id', 'goods_sn', 'color', 'size', 'weight', 'price', 'thumbnail'])->get();
        if ($specCollection) {
            $goodsCollection = GoodsPicPrimaryModel::whereIn('ID', $specCollection->pluck('goods_id'))->select(['ID', 'PName', 'Path', 'FName', 'SID'])->get();
            $data = [];
            foreach ($specCollection->toArray() as $specArray) {
                $goodsItem = $goodsCollection->where('ID', $specArray['goods_id'])->first();
                $specArray['sid'] = $goodsItem ? $goodsItem->SID : 0;
                $specArray['goods_name'] = $goodsItem ? $goodsItem->PName : '';
                $specArray['thumbnail'] = $goodsItem ? GoodsModelResource::THUMBNAIL_PREFIX . $goodsItem->Path . DIRECTORY_SEPARATOR . $goodsItem->FName : $specArray['thumbnail'];
                $data[] = $specArray;
            }
            return $data;
        } else
            return $specCollection->toArray();
    }

    /**
     * 获取商品SN列表
     * @param $array
     * @return array
     */
    private function getGoodsSns($array): array
    {
        $goodsSns = [];
        foreach ($array as $goods) {
            if ($goods[0] == '图片')
                continue;
            if ($goods[6])
                $goodsSns[] = $goods[6];
        }
        return $goodsSns;
    }
}
